package com.edou.member.controller.mobile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.constant.SessionConstant;
import com.edou.base.controller.BaseController;
import com.edou.base.util.EncryptUtil;
import com.edou.member.entity.MemberCompany;
import com.edou.member.entity.MemberLoginToken;
import com.edou.member.entity.MemberUser;
import com.edou.member.form.MemberLoginTokenForm;
import com.edou.member.service.IMemberCompanyService;
import com.edou.member.service.IMemberLoginTokenService;
import com.edou.member.service.IMemberRoleService;
import com.edou.member.service.IMemberUserRoleService;
import com.edou.member.service.IMemberUserService;
import com.edou.system.service.ISysMailService;

/**
 * 会员登录模块
 * @creator     admin
 * @create-time 2016/3/12 16:10:22
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("memberUserLoginMobileController")
@Scope("prototype")
@RequestMapping("/app/member")
public class MemberUserLoginMobileController extends BaseController {
	
	@Resource(name = "memberUserServiceImpl")
	private IMemberUserService memberUserService;
	@Resource(name = "memberCompanyServiceImpl")
	private IMemberCompanyService memberCompanyService;
	@Resource(name = "sysMailServiceImpl")
	private ISysMailService emailService;
	@Resource(name = "memberUserRoleServiceImpl")
	private IMemberUserRoleService memberUserRoleService;
	@Resource(name = "memberRoleServiceImpl")
	private IMemberRoleService memberRoleService;
	@Resource(name = "memberLoginTokenServiceImpl")
	private IMemberLoginTokenService memberLoginTokenService;
	
	
	
	
	/**
	 * 会员登录
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/login.htm", method = RequestMethod.POST)
	public ModelAndView login(@ModelAttribute MemberLoginTokenForm model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		try{
		
			String passwordEncrypt = EncryptUtil.encryptionPw(model.getPassword());	//密码加密
			
			// 验证用户名与密码是否正确
			MemberUser memberDb = memberUserService.getMemberUserByAccountAndPassword(model.getAccount(), passwordEncrypt);
			if(null == memberDb){
				return ajaxJSON(Status.error, "用户名或密码不正确");
			}
			
			// 会员的启用状态
			if(memberDb.getState() != null && memberDb.getState() == 1){
				return ajaxJSON(Status.error,"该账户已被禁用");
			}
			
			//保存会员登录信息
			model.setMemberUser(memberDb);
			memberDb.setDeviceId(model.getDeviceId());
			memberDb.setDeviceType(model.getDeviceType());
			MemberLoginToken token = memberLoginTokenService.simpleLoginToken(memberDb);;
			
			//查询会员公司信息
			MemberCompany memberCompany = memberCompanyService.getMemberCompanyByMemberUserId(memberDb.getId());
			
			//返回数据
			JSONObject root = new JSONObject();
			root.put("loginToken", token.getToken());
			root.put("chatToken", token.getChatToken());
			root.put("member", memberDb);
			root.put("company", memberCompany);
			return ajaxJSON(Status.success,"success",root);
		}catch(Exception e){
			e.printStackTrace();
			return ajaxJSON(Status.error, "登录异常，请查看系统日志");
		}
	}
	
	/**
	 * 第三方登录
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/third_login.htm", method = RequestMethod.POST)
	public ModelAndView thirdLogin(@ModelAttribute MemberLoginTokenForm model, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		try{
			//第三方登录
			memberLoginTokenService.thirdLogin(model);
			
			//返回数据
			JSONObject root = new JSONObject();
			root.put("loginToken", model.getItem().getToken());
			root.put("chatToken", model.getItem().getChatToken());
			root.put("member", model.getMemberUser());
			return ajaxJSON(Status.success,"success",root);
			
		}catch(Exception ex){
			String msg = "第三方登录发生异常：" + ex.getMessage();
			logger.error(msg,ex);
			
			return ajaxJSON(Status.error, "登录失败，请稍后重试");
		}
	}
	
	/**
	 * 登出系统
	 * @return
	 */
	@RequestMapping(value = "/logout.htm", method = RequestMethod.POST)
	public ModelAndView logout(@ModelAttribute MemberLoginTokenForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			memberLoginTokenService.delByToken(model.getToken());
			return ajaxJSON(Status.success);
		}catch(Exception ex){
			String msg = "APP端登出时发生异常：" + ex.getMessage();
			logger.error(msg,ex);
			
			return ajaxJSON(Status.error,"登出失败，请稍后重试");
		}
	}
	

	/**
	 * 更新会员在线状态
	 * @return 
	 */
	@RequestMapping(value = "/update_online_status.htm", method = RequestMethod.POST)
	public ModelAndView updateOnlineStatus(HttpServletRequest request){
		try{
			String onlineStatusStr = request.getParameter("onlineStatus");
			if(StringUtils.isBlank(onlineStatusStr)){
				return ajaxJSON(Status.error);
			}
			MemberUser currentMember = (MemberUser) request.getAttribute(SessionConstant.CURRENT_MEMBER);
			
			MemberLoginToken memberLoginToken = memberLoginTokenService.getMemberLoginTokenByMemberId(currentMember.getId());
			if(null != memberLoginToken){
				//更新在线状态
				memberLoginToken.setOnlineStatus(Integer.parseInt(onlineStatusStr));
				memberLoginTokenService.updateOnlineStatus(memberLoginToken);
			}
			return ajaxJSON(Status.success);
		}catch(Exception ex){
			String msg = "更新会员在线状态发生异常：" + ex.getMessage();
			logger.error(msg,ex);
			
			return ajaxJSON(Status.error,msg);
		}
	}
	
}